<?php
 require_once 'base.class.php';


 class onlyimage  extends  _onlyimage {
   public function __construct()
  {
    parent::__construct();
   	add_action('init', array( __CLASS__ , 'init'));
	  register_deactivation_hook( FVF_FILE , array( __CLASS__ , 'uninstall'));
  }

   function init() {
    if (is_admin() && preg_match('#[admin|image*search]#isU', $_SERVER['REQUEST_URI']) ) {
      self::check_wp_version( MYSTP_WP_MIN );
      add_action('admin_menu', array(__CLASS__, 'admin_menu'));
       add_filter('plugin_action_links_' . basename(dirname( FVF_FILE)) . '/' . basename( FVF_FILE ),
                          array(__CLASS__, 'plugin_action_links'));
      add_action('admin_init', array(__CLASS__, 'register_settings'));
      self::default_settings(false);
      add_filter('media_buttons_context', array(__CLASS__, 'media_button'));
      add_action('admin_head', array(__CLASS__, 'admin_enqueues'));

	    wp_register_script('freevf', freevf_pg_url('res/js/base.js', FVF_FILE ,array('jquery'),'2.7',true));
      wp_register_script('freevf_popup', freevf_pg_url('res/js/jquery.colorbox.js', FVF_FILE ,array('jquery'),'2.7',true));
      wp_register_style('freevf_css', freevf_pg_url('res/css/base.css',FVF_FILE));

      wp_enqueue_style('freevf_css');
      wp_enqueue_script('jquery');
      wp_enqueue_script( 'freevf_popup' );
      wp_enqueue_script( 'freevf' );

	    add_action('admin_head', array(__CLASS__, 'popup'));
      add_action('admin_print_styles', array( __CLASS__ , 'css_remove'));
      add_action('admin_print_scripts', array( __CLASS__ , 'js_remove'));
      add_action('wp_ajax_freevf_proxy', array(__CLASS__ , 'ajax_proxy'));
    }
  } // init

  function js_remove(){
    $action = isset( $_GET['action']) ? trim( $_GET['action']) : '';
    if(  $action == 'freevf_proxy' ) {
       global $wp_scripts;
       $no = array('freevf_popup' , 'freevf_scroll' ,'freevf','freevf_img');
       $jsall = $wp_scripts->registered;
      if( is_array( $jsall) && count( $jsall) ){
          foreach( $jsall as $_vjs){
              if( !in_array( $_vjs->handle , $no)) {
                if( !preg_match('#^jquery#isU' , $_vjs->handle ))
                 wp_deregister_script( $_vjs->handle );
              }//if not in  plugin
          } // foreach
      }//if array
    } //js load plugin
  }

  function css_remove(){
    $action = isset( $_GET['action']) ? trim( $_GET['action']) : '';

    if( $action == 'freevf_proxy')
   {
    global $wp_styles;
    $cssall = array();
    $cssall = $wp_styles->registered;
    $no = array('freevf_css','freevf_p_css');
    if( is_array( $cssall) && count( $cssall )){
      foreach( $cssall as $_vcss){
         if( !in_array( $_vcss->handle , $no ) ){
          $wp_styles->remove( $_vcss->handle);
         }
      }
    }
   }
  }
    //ajax show
   function ajax_proxy()
  {
    include ('onlyimageshow.php');
    ob_start();
    $view = new onlyimage_show();
    $html = $view->doAction();
    wp_enqueue_style('freevf_css');
    wp_enqueue_style('freevf_p_css');
    wp_enqueue_script("jquery");
    wp_enqueue_script('freevf');
    wp_enqueue_script("freevf_scroll");
    ob_end_flush();
    $body_id = 'media-upload';
    print _onlyimage::iframe( array($view,'out'),'image' );
   exit();
  }


   //add the  menu button
   public function admin_menu(){
	 add_options_page('Free Stock Images option',__(FVF_APPNAME , FVF_TED), 'manage_options',FVF_OPTIONS_KEY, array(__CLASS__, 'options_page'));
  }

    // add settings link to plugins page
  function plugin_action_links($links) {
    $settings_link = '<a href="options-general.php?page='.FVF_OPTIONS_KEY.'" title="'.__( FVF_APPNAME .'Plugin Settings', FVF_TED).'">'.__('Settings', FVF_TED).'</a>';
    array_unshift($links, $settings_link);
    return $links;
  }

    // complete options page markup
  function options_page() {
    if (!current_user_can('manage_options'))  {
      wp_die(__('You are not allowed to change options!', FVF_TED));
    }

    $options = get_option( FVF_OPTIONS_KEY);


    $license   = array();
    $license[] = array('val' => '2', 'label' => '2');
    $license[] = array('val' => '4', 'label' => '4');
    $license[] = array('val' => '6', 'label' => '6');
    $license[] = array('val' => '8', 'label' => '8');
    $license[] = array('val' => '10', 'label' => '10');

    $clear = array();
    $clear[] = array('val'=>'0' , 'label' => __('No',FVF_TED));
    $clear[] = array('val'=>'1' , 'label' => __('Yes',FVF_TED));

    echo '<div class="wrap">
          <div class="icon32-new icon-cf"><br /></div>
          <h2>'.__( FVF_APPNAME, FVF_TED).'</h2>';

    echo '<form action="options.php" method="post">';
    settings_fields(FVF_OPTIONS_KEY);
    echo '<table class="form-table"><tbody>';
    echo '<tr valign="top">
          <th scope="row"><label for="' . FVF_OPTIONS_KEY . '[Maxtry]">',__('API Max Attempts:', FVF_TED),'</label></th>
          <td><select name="' . FVF_OPTIONS_KEY . '[Maxtry]">';
          self::create_select_options($license, $options['Maxtry']);
    echo '</select>';
    echo '</td></tr>';

    echo '<tr valign="top">
             <th scope="row"><label >',__('Reset plugin cache:', FVF_TED),'</label></th>
            <td><select name="' . FVF_OPTIONS_KEY . '[clear]">';
          self::create_select_options($clear,  'No');
    echo '</select>';
    echo   '</td></tr>';

    echo '</tbody></table>';

    echo '<p class="submit"><input type="submit" value="',__('Save', FVF_TED),'" class="button-primary" name="Submit" /></p>';

    echo '</form>';
    echo '</div>';
  } // options_page

   // all settings are saved in one option key
  function register_settings() {
    register_setting( FVF_OPTIONS_KEY, FVF_OPTIONS_KEY, array(__CLASS__, 'sanitize_settings'));

  } // register_settings

  // helper function for creating dropdowns
  function create_select_options($options, $selected = null, $output = true) {
    $out = "\n";

    foreach ($options as $tmp) {
      if ($selected == $tmp['val']) {
        $out .= "<option selected=\"selected\" value=\"{$tmp['val']}\">{$tmp['label']}&nbsp;</option>\n";
      } else {
        $out .= "<option value=\"{$tmp['val']}\">{$tmp['label']}&nbsp;</option>\n";
      }
    } // foreach

    if ($output) {
      echo $out;
    } else {
      return $out;
    }
  } // create_select_options

  // sanitize settings on save
  function sanitize_settings($values) {
    $old_options = get_option(FVF_OPTIONS_KEY);

    foreach ($values as $key => $value) {
      switch ($key) {
        case 'Maxtry':
            $values[$key] = intval($value) < 2 ? self::$Maxtry : (intval($value) > 15 ? self::$Maxtry : intval($value));
           break;
        case 'clear':
          if( intval($values[$key]) ){
              $bdir = FVF_PATH .'cache/';
              if( file_exists($bdir .FVF_CACHE_LIST.'.cache' )  )
                 @unlink( $bdir .FVF_CACHE_LIST.'.cache' );
              if( $bdir .'freevf_home_bgimage.cache' )
                @unlink( $bdir .'freevf_home_bgimage.cache' );
          }
          unset($values['clear']);
        break;
      } // switch
    } // foreach
    return array_merge($old_options, $values);
  }

   // add media button
  function media_button($editor) {
	   $post_id = isset( $_REQUEST['post_id'] )? intval( $_REQUEST['post_id'] ) : 0;
	    if (!$post_id) {
        global $post_ID, $temp_ID;
        $post_id = (int) (0 == $post_ID ? $temp_ID : $post_ID);
    }
  $mystp_btn  = '<a href="'.admin_url('admin-ajax.php?action=freevf_proxy&show=index');
	$mystp_btn .= $post_id ? '&post_id='.$post_id : '';
	$mystp_btn .= '"  class="freevf_popup " title="'.__('Free Stock Images - Add Images to Blog Posts', FVF_TED).'"> <span class="freevf-button-pop"></span></a>';

   return $editor.$mystp_btn;
  } // media_button

   // admin enqueue
  function admin_enqueues() {
    if (strpos($_SERVER['REQUEST_URI'], 'show.php') !== false) {
      echo '<script type="text/javascript">if(typeof(ajaxurl) ==  "undefined" ){ var ajaxurl = "' . admin_url('admin-ajax.php') . '";}</script>';
     }
 }

    //pop up div js event bind
   function popup(){
    echo "<style> .freevf-button-pop {background: url('";
    echo freevf_pg_url('res/images/button.png', FVF_FILE ) ;
    echo "') no-repeat top left;display: inline-block;vertical-align: text-top;margin: 0 2px;width:88px;height:18px;margin-bottom:10px;}</style>";
    echo "<script type='text/javascript'>";
    echo " jQuery(document).ready( function($){ $('.freevf_popup').colorbox({iframe:true, innerWidth:1000 , innerHeight:780 , title:false, closeButton:false, scrolling:false ,opacity:0.65 });}); ";
    echo "</script>";
   }

  // check if user has the minimal WP version required by the plugin
  function check_wp_version($min_version) {
    if (!version_compare(get_bloginfo('version'), $min_version,  '>=')) {
        add_action('admin_notices', array(__CLASS__, 'min_version_error'));
    }
  } // check_wp_version

   // min version error
  function min_version_error() {
    echo '<div class="error"><p>',__('Free Stock Images', FVF_TED),'<b>',__('This plugin requires WordPress version ', FVF_TED),'<b>',__(' or higher. Current installed is version ', FVF_TED),get_bloginfo('version'),__('Please <a href="update-core.php">Upgrade</a> your WordPress installation.' , FVF_TED);
  } // min_version_error

  function uninstall() {
    delete_option( FVF_OPTIONS_KEY );
  }

  // set default settings
  function default_settings($force = false) {
    $defaults = array('page_length' => '25',
                      'Maxtry' => '6'
                );

    $options = get_option( FVF_OPTIONS_KEY );

    if(empty($options['Maxtry'])) {
      $options['Maxtry'] = self::$Maxtry;
      update_option(FVF_OPTIONS_KEY, $options);
    }
  } // default_settings

}